package com.iflytek.yousheng.Util;

import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkHttp3Utils {

    private static OkHttpClient okHttpClient = null;

    public static final int OKHTTP_CONNECT_TIME = 5;

    public static final int OKHTTP_READ_TIME = 60;

    public static final int OKHTTP_WRITE_TIME = 60;

    public static final String UTF8 = "utf-8";

    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    public static final MediaType CONTENT_TYPE_TEXT = MediaType.parse("application/text-html;charset=utf-8");
    public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded;charset=utf-8");

    private OkHttp3Utils() {
    }

    static {
        if (okHttpClient == null) {
            //加同步安全
            synchronized (OkHttp3Utils.class) {
                if (okHttpClient == null) {
                    //构建器
                    okHttpClient = new OkHttpClient.Builder()
                            //连接超时
                            .connectTimeout(OKHTTP_CONNECT_TIME, TimeUnit.SECONDS)
                            //写入超时
                            .writeTimeout(OKHTTP_WRITE_TIME, TimeUnit.SECONDS)
                            //读取超时
                            .readTimeout(OKHTTP_READ_TIME, TimeUnit.SECONDS)
                            .build();
                }
            }
        }
    }


    public static String postJson(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        System.out.printf("Post请求URL:%s,参数:%s \n", url, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        long start = System.currentTimeMillis();
        Response response = okHttpClient.newCall(request).execute();
        long end = System.currentTimeMillis();
        System.out.printf("%s,接口耗时:%dms", url, end - start);
        return response.body().string();
    }


    public static byte[] postByte(String url, byte[] data) throws IOException {
        RequestBody body = RequestBody.create(JSON, data);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().bytes();

    }
}
